package com.ciwong.epaper.modules.evaluate.util;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.evaluate.bean.Sentence;
import com.ciwong.epaper.modules.evaluate.bean.SentenceAnswerBean;
import com.ciwong.epaper.modules.evaluate.ui.SentenceRepeatActivity;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.libs.oralevaluate.IEvaluateEngine;
import com.ciwong.libs.oralevaluate.OnEvaluateListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.oralevaluate.yunzhisheng.YZSEngine;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.SDKError;

import java.io.File;

/**
 * @description:句子跟读重新评分工具类
 * @author: wyk
 * @time: 2021/8/2 8:50
 */
public class SentenceResultScoreController implements OnEvaluateListener {

    protected IEvaluateEngine eEngine;

    protected BaseActivity mContext;

    protected String mUuid;

    protected SentenceAnswerBean mSentenceAnswerBean;

    protected Sentence mSentence;

    private SentenceResultInterFace sentenceResultInterFace;

    private boolean mIsSubmitAll;


    /**
     * 年级id
     */
    private int mGradeId;
    /**
     * 是否是最后一个需要评分的单词
     */
    private boolean mIsLastOne;
    //作业开始时间
    private long startTime;
    /**
     * 默认服务包剩余使用时间
     */
    public boolean serviceExpired;

    public SentenceResultScoreController(BaseActivity mContext, String uuid, long startTime,boolean serviceExpired) {
        this.mContext = mContext;
        this.mUuid = uuid;
        this.startTime = startTime;
        this.serviceExpired = serviceExpired;
        try {
            initYZSEngine();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 初始化
     */
    protected void initYZSEngine() {
        if (EApplication.getInstance().getClazz() != null) {
            mGradeId = EApplication.getInstance().getClazz().getGradeId();
        }
        eEngine = new YZSEngine(mContext);
        if (mGradeId >= 1101 && mGradeId <= 1106) {
            eEngine.SetScoreAdjuest(1.8f);
        } else {
            eEngine.SetScoreAdjuest(1.7f);
        }
        eEngine.setEvaluateListener(SentenceResultScoreController.this);


    }

    public void scoreReTry(SentenceAnswerBean sentenceAnswerBean, Sentence sentence, boolean mIsLastOne, boolean isSubmitAll) {
        this.mSentenceAnswerBean = sentenceAnswerBean;
        this.mSentence = sentence;
        this.mIsSubmitAll = isSubmitAll;
        String wordText;
        String soundUrl;
        try {
            String sentenceText = sentence.getText();
            String processText = SpeechUtils.replaceEvaluateText(sentenceText);
            processText = SpeechUtils.replaceAsSpace(processText);
            eEngine.setText(processText);
            eEngine.setConnectTimeout(30000);
            //音频opus文件地址
            soundUrl = getSoundOpusPath(sentence).getAbsolutePath();
            UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
            if (null != userInfoBase) {
                eEngine.setUid(String.valueOf(userInfoBase.getUserId()));
            }
            eEngine.retry("C", processText, soundUrl, true);
        } catch (
                NullPointerException e) {
            e.printStackTrace();
        } catch (
                OutOfMemoryError error) {
            error.printStackTrace();
        }

    }

    /**
     * 获取录音的地址
     *
     * @param sentence
     * @return
     */
    private File getSoundPath(Sentence sentence) {
        return new File(ESystem.getAnswersUserIdMediaPathSentence(mUuid),
                mUuid + StringUtils.md5(sentence.getText()) + "&" + startTime
                        + EConstants.AUDIO_DEFAULT_SUFFIX);
    }

    /**
     * 获取录音Opus的地址
     *
     * @param sentence
     * @return
     */
    private File getSoundOpusPath(Sentence sentence) {
        return new File(ESystem.getAnswersUserIdMediaOpusPathSentence(mUuid),
                mUuid + StringUtils.md5(sentence.getText()));
    }

    @Override
    public void onInit(int i) {

    }

    @Override
    public void onError(IOralEvalSDK iOralEvalSDK, SDKError sdkError, IOralEvalSDK.OfflineSDKError offlineSDKError) {
        if (mContext instanceof SentenceRepeatActivity) {
            ((SentenceRepeatActivity) mContext).addScoreCount();
        }
        if (null != sentenceResultInterFace) {
            sentenceResultInterFace.reFresh();
        }
        SDKError.Category category = sdkError.category;

    }

    @Override
    public void onStart() {

    }

    @Override
    public void onVolume(int i) {

    }

    @Override
    public void onStop(int i, EvaluateResult eResult, String url) {
        final int score = (int) eResult.getScore();
        String lines = JsonParserUtil.toJson(eResult);
        // 把结果添加到结果结合中去,音频文件地址
        StringBuffer sb = new StringBuffer(ALiYunManager.ACCESS_URL);

        sb.append("work/followread/" + CWUtils.getReadTime(startTime) + "/"
                + CWSys.getSharedLong(
                BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0)
                + "/");
        mSentence.setScore((int) eResult.getScore());
        mSentence.setHasGrade(true);
        mSentence.setSoundUrl(getSoundPath(mSentence
        )
                .getAbsolutePath());
        sb.append(mUuid + StringUtils.md5(mSentence.getText()));
        sb.append(EConstants.AUDIO_DEFAULT_SUFFIX);
        mSentenceAnswerBean.setLines(lines);
        mSentenceAnswerBean.setSentence(mSentence);
        mSentenceAnswerBean.setYzsAudioUrl(url);
        if (mContext instanceof SentenceRepeatActivity) {

            ((SentenceRepeatActivity) mContext).addScoreCount();
            //((SentenceRepeatActivity) mContext).setScoreResultReTry(mSentenceAnswerBean,mIsLastOne);
            if (null != sentenceResultInterFace) {
                sentenceResultInterFace.setScoreResultReTry(mSentenceAnswerBean, mIsLastOne, mIsSubmitAll);
            }
            if (!mIsLastOne) {
                ((SentenceRepeatActivity) mContext).scoreReTryCommit();
            }

        }
    }

    @Override
    public void onStartOralEval() {

    }

    public void setSentenceResultInterFace(SentenceResultInterFace sentenceResultInterFace) {
        this.sentenceResultInterFace = sentenceResultInterFace;
    }

    public interface SentenceResultInterFace {
        void showResult(EvaluateResult eResult, Sentence sentence, boolean isFill);

        void setScoreResultReTry(SentenceAnswerBean scoreResultReTry, boolean isLastOne,boolean isSubmitAll);

        void reFresh();

        void scoreError();
    }
}
